function pv = makelabel(pv, withdots)
% makelabel  - returns a valid label from input
%
% when a valid label/identifier name is required from a string,
% this function returns a validated string that can be used.
%
% FORMAT:       vlabel = makelabel(testlabel [,withdots])
%
% Input fields:
%
%       testlabel   string to use for label generation
%       withdots    if argument is specified, struct-like
%                   identifier are accepted
%
% Output fields:
%
%       vlabel      string that can be used for a label name
%
% See also isrealvarname.

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1
    error( ...
        'BVQXtools:TooFewArguments',...
        'Too few arguments. Try ''help %s''.',...
        mfilename ...
    );
end

% some first checks
if ~ischar(pv)
    pv = '';
end
pv = deblank(pv(:)');

% empty variable ...
if isempty(pv)
    pv = sprintf('V_%010.0f', floor(2 ^ 31 * rand(1)));

% not with dots
elseif nargin == 1

    % return name if already is varname
    if isrealvarname(pv)
        return;
    end

    % otherwise check first character and prepend 'V_' if necessary
    pa = pv(1);
    if pa < 65 || ...
       (pa > 90 && pa < 97) || ...
        pa > 122
        pv = ['V_' pv];
    end

    % replace all bad chars with underscores
    pv(pv < 48 | (pv > 57 & pv < 65) | (pv > 90 & pv < 95) | pv == 96 | pv > 122) = '_';

    % replace double underscores with single ones
    while ~isempty(strfind(pv, '__'))
        pv = strrep(pv, '__', '_');
    end

    % get correct variable size
    pv = pv(1:min(namelengthmax, size(pv,2)));

% with dots
elseif ~isempty(withdots)
    % split to single names (at dots)
    [pcs, pcc] = splittocell(pv, '.', 1);

    % check vor every part
    for pcc = 1:pcc
        pcp = pcs{pcc};

        % allow sub-indexing (remove from name)
        pcb = regexp(pcp,'\(\d+[\,\d]*\)$');
        if ~isempty(pcb)
            pcx = pcp(pcb(1):end);
            pcp(pcb(1):end) = [];
        else
            pcx = '';
        end

        % test remaining string and recode if needed
        if ~isrealvarname(pcp)
            pcs{pcc} = [makelabel(pcp) pcx];
        end
    end

    % make a dotted expression again
    pv = gluetostring(pcs, '.');
end
